package com.yhx.job;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.Set;

@Component
public class CleanJob {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Value("${download.path}")
    private String path;
    //定时操作，每个小时删除一次
    @Scheduled(cron = "0 14 * * * *")
    public void clean(){
        //操作set集合
        SetOperations<String, String> opsForSet = stringRedisTemplate.opsForSet();
        //求redis中两个set集合的差集，pic_list中是所有图片，db_list是还存在数据库的图片，差集就是垃圾图片
        Set<String> difference = opsForSet.difference("pic_list", "db_list");
        //如果垃圾图片存在
        if(difference!=null || difference.size()>0){
            //有垃圾图片
            for (String s : difference) {
                //对文件名进行截取，只保留文件名
                s=s.substring(12);
                //path+s=图片的全路径
                File file = new File(path + s);
                if(file.exists()){
                    file.delete();
                }

            }
        }
        //清除redis的数据
        stringRedisTemplate.delete("pic_list");
        stringRedisTemplate.delete("db_list");
        System.out.println("清理成功");
    }
}
